#include "stdafx.h"
#include "sysdebug.h"
#include "sysapi.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>   //mmap
#include <linux/fb.h>


#include "hi_common.h"
#include "hi_type.h"
#include "hi_comm_vb.h"
#include "hi_comm_sys.h"
#include "hi_comm_venc.h"
#include "hi_comm_vi.h"
#include "hi_comm_vo.h"
//#include "hi_comm_group.h"
#include "hi_comm_region.h"
#include "mpi_vb.h"
#include "mpi_sys.h"
#include "mpi_venc.h"
#include "mpi_vi.h"
#include "mpi_vo.h"
#include "mpi_region.h"
#include "sample_comm.h"

#include <linux/fb.h>
#include "hifb.h"
#include "loadbmp.h"
#include "hi_comm_ive.h"
#include "mpi_ive.h"

#include "hi_tde_api.h"
#include "hi_tde_type.h"
#include "hi_tde_errcode.h"

#include "hi_common.h"
#include "hi_type.h"
#include "hi_comm_vb.h"
#include "hi_comm_sys.h"
#include "hi_comm_venc.h"
#include "hi_comm_vi.h"
#include "hi_comm_vo.h"
//#include "hi_comm_group.h"
#include "hi_comm_region.h"
#include "mpi_vb.h"
#include "mpi_sys.h"
#include "mpi_venc.h"
#include "mpi_vi.h"
#include "mpi_vo.h"
#include "mpi_region.h"
#include "sample_comm.h"

#include <opencv2/core/core.hpp>
#include <opencv2/opencv.hpp>

#include "mvMat.h"

using namespace cv;
using namespace std;

CmvMat::CmvMat()
{
	m_u32PhyAddr = 0;
	m_pVirtAddr = NULL;

	initEmpty();
}

CmvMat::~CmvMat()
{
	freeMmz();

	m_u32PhyAddr = 0;
	m_pVirtAddr = NULL;
}

u32 CmvMat::getPhyAddr()
{
	return m_u32PhyAddr;
}

void* CmvMat::getVirtAddr()
{
	return m_pVirtAddr;
}


int CmvMat::createImage(Size size, int type)
{
	flags = type & TYPE_MASK;
	dims = 2;
	rows = size.height;
	cols = size.width;
	step = size.width * channels();

	this->data = (uchar *)newMmz(size.width*size.height*channels());
	if (this->data == NULL)
	{
		Debug(DEBUG_CRITICAL, ("####CmvMat::createImage(): mmz memory err!!!\r\n"));
		return -1;
	}
	return 0;
}


void* CmvMat::newMmz(u32 numBytes)
{
	if (m_pVirtAddr!=NULL && m_u32PhyAddr!=0)
	{
		return m_pVirtAddr;
	}

	u32 size = (numBytes+7)/8*8;

	Debug(DEBUG_CRITICAL, ("####CmvMat::mallocMmz(): mmz memory size!!!\r\n", size));

	int s32Ret = HI_MPI_SYS_MmzAlloc((HI_U32 *)&m_u32PhyAddr,	&m_pVirtAddr, "user", HI_NULL, size);

	if (s32Ret != HI_SUCCESS)
	{
		freeMmz();
		Debug(DEBUG_CRITICAL, ("####CmvMat::mallocMmz(): mmz memory err!!!\r\n"));
		return NULL;
	}

	return m_pVirtAddr;
}


void CmvMat::freeMmz()
{
	if (m_pVirtAddr!=NULL && m_u32PhyAddr!=0)
	{
		HI_MPI_SYS_MmzFree(m_u32PhyAddr, m_pVirtAddr);
	}

	m_u32PhyAddr = 0;
	m_pVirtAddr = NULL;
}

